from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage
from apps.meiduo_admin.serializers.sku_image import ImageSerializer
from apps.meiduo_admin.utils.pagination import MeiduoPagination


class ImageViewSet(ModelViewSet):
    pagination_class = MeiduoPagination
    queryset = SKUImage.objects.all().order_by('-id')
    serializer_class = ImageSerializer

    #重写create方法 里面需要进行图片的上传
    def create(self,request,*args,**kwargs):
        #接受
        sku = request.data.get('sku')
        image = request.data.get('image')
        #验证
        if not all([sku,image]):
            return Response({'detail':'数据不完整'},status=400)
        #处理 上传图片  创建图片对象

        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = image_client.upload_by_buffer(image.read())

        image_name = data.get("Remote file_id")
        #创建图片模型对象
        instance = SKUImage.objects.create(sku_id=sku,image = image_name)

        serializer = self.get_serializer(instance)
        return Response(serializer.data,status=201)
    def update(self,request,*args,**kwargs):
        #获取当前要修改的图片对象
        instance = self.get_object()
        #接受
        sku_id = request.data.get('sku')
        image = request.data.get('image')
        #验证
        if not all([sku_id]):
            return Response({'detail':"数据不完整"},status=400)
        #处理   删除图片 如果用户上传则修改  修改 删除后直接上传
        if image:
            image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
            #删除   instance.image.name   获取图片的名字字符串
            image_client.delete_file(instance.image.name)
            #上传
            data = image_client.upload_by_buffer(image.read())
            instance.image = data.get('Remote file_id')
        # 修改对象
        instance.sku_id = sku_id
        instance.save()
        #响应
        serializer = self.get_serializer(instance)
        return Response(serializer.data,status=201)
    def destroy(self, request, *args, **kwargs):
        #查询当前对象
        instance = self.get_object()

        #删除图片
        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        image_client.delete_file(instance.image.name)
        #删除数据
        instance.delete()
        #响应对象
        return Response(status=204)